package org.wang.gift.service.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.wang.gift.dto.SmsCodeDto;
import org.wang.gift.exception.asserts.Assert;
import org.wang.gift.exception.code.StatusCode;
import org.wang.gift.service.IVerifyCodeService;
import org.wang.gift.util.AjaxResult;
import org.wang.gift.util.StrUtils;

import java.util.Date;
import java.util.concurrent.TimeUnit;
@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${sms.code.register.resend-time}")
    private Integer resendTime;
    @Value("${sms.code.register.expire-time}")
    private Integer expireTime;
    @Override
    public AjaxResult sendSmsCodeRegister(String mobile) {
        //处理短信验证码
        String key= "register_sms_code_" + mobile;
        //通过key查询redis里面是否有短信验证码
        String smsCodeOfRedis = (String) redisTemplate.opsForValue().get(key);
        String phonecode="";
        //如果为空产生一个六位的验证码
        if (StringUtils.isEmpty(smsCodeOfRedis))
            phonecode= StrUtils.getRandomString(6);
        else {
            //2.2 如果存在，判断是否已过重发时间，如果没有过报错，过了直接原来的
            //由于验证码是code：time的形式  拿到验证码和时间
            phonecode = smsCodeOfRedis.split(":")[0];
            String time = smsCodeOfRedis.split(":")[1];
            //判断时间是否过期
            //通过当前时间戳来减去时间
            if (System.currentTimeMillis() - new Date(Long.valueOf(time)).getTime() <= 60 * 1000 * resendTime) {
                return AjaxResult.me().setSuccess(false).setMessage("请在60秒之后重新发送");
            }
        }
        //3 记录验证码到redis
        redisTemplate.opsForValue().set(key,phonecode+":"+System.currentTimeMillis(),expireTime, TimeUnit.MINUTES);
        //发送短信
        String content = String.format("你的验证码为%s,请在%s分钟之内使用！", phonecode, expireTime);
        //SmsUtil.sendSms(mobile, content);
        System.out.println("已经成功发送了一条短信,内容为"+content);
        return AjaxResult.me();
    }

    @Override
    public AjaxResult validationSmsCode(SmsCodeDto smsCodeDto) {
        String mobile = smsCodeDto.getMobile();
        String smsCode = smsCodeDto.getCode();
        String key = "register_sms_code_" + mobile;
        String code = (String) redisTemplate.opsForValue().get(key);
        Assert.assertNotEqualsIgnoreCase(smsCode,code, StatusCode.CODE_400_SMSCODE_ERROR);
        redisTemplate.delete(key);
        return AjaxResult.me();
    }
}
